package com.ganzalang.gmall.redis.service.impl;

import com.ganzalang.gmall.redis.service.RedisService;
import io.lettuce.core.cluster.RedisClusterClient;
import io.lettuce.core.cluster.api.StatefulRedisClusterConnection;
import io.lettuce.core.cluster.api.sync.RedisAdvancedClusterCommands;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Author Androidla
 * @Date 2021/2/14 13:30
 * @Description
 **/
@Service
@Slf4j
public class TestServiceImpl {

    @Autowired
    private RedisService redisService;

    @Value("${redis.key.authCode}")
    private String REDIS_KEY_AUTH_CODE;

    @Value("${redis.expire.authCode}")
    private Long REDIS_EXPIRE_AUTH_CODE;

    @Autowired
    private StatefulRedisClusterConnection connection;


    public void testRedis() {
        log.info("test start ...");
        String key = REDIS_KEY_AUTH_CODE + "10010";
        redisService.set(key, "管理员权限");
        redisService.expire(key, REDIS_EXPIRE_AUTH_CODE);
        String value = (String) redisService.get(key);
        log.info("value is : {}", value);
        log.info("value is : {}", value);
        log.info("value is : {}", value);
        log.info("value is : {}", value);
        log.info("value is : {}", value);
    }

    public void readFromReplica() {
        String key = "10010";
        log.info("read from replica...");
        log.info("connection class is: {}", connection.getClass());
        RedisAdvancedClusterCommands sync = connection.sync();

        sync.set(key, "中国联通");
        Object value = sync.get(key);
        log.info("value is: {}", value);

        // 官方文档上是有将connection以及client关闭掉的
//        connection.close();
//        client.shutdown();

    }
}
